package com.asia5b.a5mall.shop.fragment

import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.logic.viewmodel.shop.ShopHomeFragmentVM
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.DisplayUtils
import com.asia5b.a5mall.middleware.utils.judge
import com.asia5b.a5mall.middleware.utils.newEmptyView
import com.asia5b.a5mall.middleware.widget.GridSpacingItemDecoration
import com.asia5b.a5mall.shop.adapter.ShopHomeAdapter
import com.asia5b.a5mall.shop.databinding.FragmentShophomeBinding
import kotlinx.android.synthetic.main.fragment_shophome.*

/**
 * Created by zhangyuncai on 2019/12/21.
 * @Note   商品首页
 */
class ShopHomeFragment : SimpleFragment<ShopHomeFragmentVM, FragmentShophomeBinding>() {
    override val viewModelClazz: Class<ShopHomeFragmentVM>
        get() = ShopHomeFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentShophomeBinding {
        return FragmentShophomeBinding.inflate(layoutInflater, container, false)
    }

    val mDatas = arrayListOf<AbsGoodsModel>()
    val mRecyclerView by lazy { rv_shophome }
    val mAdapter by lazy { ShopHomeAdapter(mDatas) }
    val emptyView by lazy { newEmptyView(mActivity) }
    var shopId: Int = 0

    override fun initView() {
        arguments?.let {
            shopId = requireArguments().getInt("shopId", 0)
        }
        val gridSpacingItemDecoration = GridSpacingItemDecoration(2, DisplayUtils.dip2px(mActivity, 3f), true)
        val gridLayoutManager = GridLayoutManager(mActivity, 2)!!
        mRecyclerView.run {
            layoutManager = gridLayoutManager
            adapter = mAdapter
            addItemDecoration(gridSpacingItemDecoration)
        }
        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(p0: Int): Int {
                val type = mAdapter.getItemViewType(p0)
                return (type == 0).judge(1, 2)
            }
        }
    }

    override fun initEvent() {

    }

    override fun startObserver() {
        mViewModel.getFirstGoodsDatasResultLiveData.observe(this, Observer {
            getFirstGoodsDatasResult(it)
        })
    }

    override fun lazyFetchData() {
        mViewModel.getFirstGoodsDatas(shopId)
    }

    fun getFirstGoodsDatasResult(data: ArrayList<AbsGoodsModel>) {
        if (emptyView.parent == null) {
            mAdapter.setEmptyView(emptyView)
        }
        mDatas.clear()
        mDatas.addAll(data)
        mAdapter.notifyDataSetChanged()
    }
}